﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sitecore.Data.Items;
using Workflow.Alerts.DAL;
using System.Data;
using workflow.Dal;

namespace Workflow.Alerts
{
    public class NewAlertViewPresenter : Presenter
    {
        #region members

        private readonly NewAlertDAL model;
        private readonly INewAlertView view;

        #endregion

        #region constructor
        public NewAlertViewPresenter(INewAlertView _view)
            : this(_view, null)
        { }

        public NewAlertViewPresenter(INewAlertView _view, ISessionProvider session)
            : base(_view, session)
        {
            view = base.GetView<INewAlertView>();
            view.OnNewAlertLoad += view_OnLoad;
            view.OnNewAlertSave += view_OnSave;
            //view.LoadMunicipalityData += view_LoadMunicipalityData;    V2.0
            view.DeleteAlert += view_DeleteAlert;

            model = new NewAlertDAL();
        }

        #endregion

        #region private methods

        private void view_OnSave(WorkflowEnums.Status status)
        {

            using (WorkflowEntitySet context = new WorkflowEntitySet())
            {
                Alert dbAlert;

                if (view.Id.HasValue)
                {
                    dbAlert = context.Alert.Include("TrafficComments").Where(a => a.id == view.Id.Value).First();
                }
                else
                {
                    dbAlert = new Alert();
                    context.AddToAlert(dbAlert);
                    dbAlert.code = GenerateAlertCode();
                    var networkoperator = context.NetworkOperator.Where(no => no.id == CurrentUser.TypeId).First();
                    dbAlert.NetworkOperator = networkoperator;
                    dbAlert.networkoperatorname = networkoperator.name;
                }

                dbAlert.alerttype = view.AlertType;
                dbAlert.activitytype = view.ActivityType;
                dbAlert.estimatestartdate = view.EstimateStartDate;
                dbAlert.estimateenddate = view.EstimateEndDate;
                dbAlert.currentstatus = (int)status;
                dbAlert.estimatearea = view.AlertArea;
                dbAlert.trafficproblems = view.HasTrafficProblems;
                dbAlert.coordinates = view.CenterCoordinates;
                dbAlert.location = view.Location;
                var municipality = context.Municipality.Where(m => m.id == view.Municipality).First();
                dbAlert.Municipality = municipality;
                dbAlert.municipalityname = municipality.name;
                dbAlert.ContactNetworkUser = context.Person.Where(p => p.id == view.Person).First();
                var user = context.Person.Where(p => p.id == CurrentUser.Id).First();
                dbAlert.CreatedNetworkUser = user;

                if (dbAlert.TrafficComments != null &&
                    dbAlert.TrafficComments.Any())
                {
                    context.DeleteObject(dbAlert.TrafficComments.FirstOrDefault());
                    dbAlert.TrafficComments.Clear();
                }

                if (!string.IsNullOrEmpty(view.TrafficComments))
                {
                    var comments = new TrafficComments();
                    context.AddToTrafficComments(comments);
                    comments.Alert = dbAlert;
                    comments.comment = view.TrafficComments;
                    comments.createddatetime = DateTime.Now;
                    comments.Person = user;
                }

                AlertHistory ah = new AlertHistory();
                context.AddToAlertHistory(ah);
                ah.Alert = dbAlert;
                ah.date = DateTime.Now;
                ah.Person = user;
                ah.status = (int)status;


                context.SaveChanges();
            }
        }

        private string GenerateAlertCode()
        {
            var name = CurrentUser.Password.Substring(0, 3);
            return string.Format("{0}{1}", name.Trim(), new Random().Next(99999));
        }

        private void view_OnLoad()
        {
            view.AlertTypeList = WorkflowEnums.AlertTypeList;
            view.ActivityTypeList = WorkflowEnums.ActivityTypeList;
            WorkflowFilter filter = new WorkflowFilter
            {
                NetworkOperatorId = CurrentUser.TypeId
            };

            WorkflowFilterSql filterSql = new WorkflowFilterSql(filter);
            view.MunicipalityList = model.GetMunicipalityByNetworkOperator(filterSql);
            view.PersonList = model.GetPersonList(filterSql);
            view.Person = CurrentUser.Id;
            view.HasTrafficProblems = false;
            view.IsMarker = true;

            if (view.Id.HasValue)
            {
                filter.AlertId = view.Id;
                view_OnSavedAlertLoad(filter);
            }
        }

        private void view_OnSavedAlertLoad(WorkflowFilter filter)
        {
            AlertViewDAL dal = new AlertViewDAL();
            var alerts = dal.GetAlertDetails(new WorkflowFilterSql(filter));
            if (alerts.Count == 1)
            {
                var alertDO = alerts[0];
                view.Municipality = alertDO.municipalityid;

                view.IsMarker = true;
                view.Location = alertDO.location;

                view.CenterCoordinates = alertDO.coordinates;
                view.AlertType = alertDO.alerttype;
                view.ActivityType = alertDO.activitytype;
                view.AlertArea = alertDO.estimatearea;
                view.EstimateStartDate = alertDO.estimatestartdate;
                view.EstimateEndDate = alertDO.estimateenddate;

                using (WorkflowEntitySet context = new WorkflowEntitySet())
                {
                    var alert = context.Alert.Include("TrafficComments").Where(a => a.id == view.Id).First();
                    view.HasTrafficProblems = alert.trafficproblems;
                    if (alert.TrafficComments.FirstOrDefault() != null)
                        view.TrafficComments = alert.TrafficComments.First().comment;
                }
            }
        }

        private void view_DeleteAlert()
        {
            model.DeleteAlert(view.Id.Value, CurrentUser.Id);
        }
        #endregion
    }
}
